<?php

declare(strict_types=1);

namespace App\JsonRpc\ServiceProvider;

use App\Service\OilChannelService;
use Hyperf\RpcServer\Annotation\RpcService;
use App\Service\AmountService as Amount;
use App\Utils\ServerUtil;
use App\Validate\AmountValidation;
use App\Utils\ApiUtils;
use Hyperf\Utils\ApplicationContext;
use App\Constants\ErrorCode;

/**
 * 注意，如希望通过服务中心来管理服务，需在注解内增加 publishTo 属性
 *
 */
class AmountService implements AmountServiceInterface
{
    public function consume($data): string
    {
        $data = json_decode($data, true);
        ServerUtil::info('rpc-AmountService-进入', ['param' => $data]);
        $type = $data['type'] ?? '';
        $obj = ApplicationContext::getContainer()->get(Amount::class);
        switch ($type) {
            case 1: //校验话费金额是否合法
                make(AmountValidation::class)->check($data, 'rpcLegalDisCountAmount')->response();
                $res = $obj->isLegalDisCountAmount($data['ori_amount'], $data['amount'], $data['type_id']);
                ServerUtil::info('rpc-AmountService-校验金额是否合法', ['param' => $data, 'res' => $res]);
                if (!$res) {
                    $responseData = json_encode(ApiUtils::send(ERRORCODE::ERR_BUESSUS, '金额不合法', $res));
                } else {
                    $responseData = json_encode(ApiUtils::send(ErrorCode::SUCCESS, '金额合法', $res));
                }
                break;
            case 2: //校验油卡金额是否合法
                make(AmountValidation::class)->check($data, 'rpcLegalDisCountAmount')->response();
                $res = $obj->isOilLegalDisCountAmount($data['ori_amount'], $data['amount'], $data['type_id']);
                if (!$res) {
                    $responseData = json_encode(ApiUtils::send(ERRORCODE::ERR_BUESSUS, '金额不合法', $res));
                } else {
                    //获取合作商信息
                    $item_id=$res['item_id'];
                    $res = make(OilChannelService::class)->amountByChannelInfo($data['ori_amount'], $data['amount'], $data['type_id']);
                    $res['item_id']=$item_id;//追加商品编号
                    if (!$res) {
                        $responseData = json_encode(ApiUtils::send(ErrorCode::ERR_BUESSUS, '没有可用的合作商'));
                    } else {
                        $responseData = json_encode(ApiUtils::send(ErrorCode::SUCCESS, '获取成功', $res));
                    }
                }
                ServerUtil::info('rpc-AmountService-校验金额是否合法', ['param' => $data, 'res' => $res]);
                break;
            default:
                $responseData = json_encode(ApiUtils::send(ERRORCODE::ERR_BUESSUS, 'type解析失败'));
        }

        return $responseData;
    }
}
